﻿using BackupByFTP.LoggerFile;
using FluentFTP;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;

namespace BackupByFTP.FluentFTPHeilpers
{
    public class FluentHeilper
    {
        /// <summary>
        ///按钮开关 0-开 1-关
        /// </summary>
        public static int BAKBTNPOWER = 0;
        /// <summary>
        /// 备份开关 0-开 1-关
        /// </summary>
        public static int BAKPOWER = 0;
        /// <summary>
        /// 按钮开关 0-开 1-关
        /// </summary>
        public static int PICBTNPOWER = 0;
        /// <summary>
        /// 备份开关 0-开 1-关
        /// </summary>
        public static int PICPOWER = 0;
        /// <summary>
        /// 文件大小 单位字节byte B
        /// </summary>
        public static long FileSize = 0;
        /// <summary>
        /// 是否已经备份  0-否  1-是
        /// </summary>
        public static int IsAlreadyBackup = 0;
        /// <summary>
        /// 获取Bak文件列表
        /// </summary>
        /// <param name="ftpServerIP">FTP服务器IP</param>
        /// <param name="ftpUserID">FTP登录帐号</param>
        /// <param name="ftpPassword">FTP登录密码</param>
        /// <returns></returns>
        public List<FileInfo> GetBakFileList(string ftpServerIP, string ftpUserID, string ftpPassword, int ftpBakServerPort)
        {
            try
            {
                using (FtpClient _ftp = new FtpClient(ftpServerIP, ftpUserID, ftpPassword, ftpBakServerPort))
                {
                    _ftp.Encoding = Encoding.UTF8;
                    _ftp.Connect();
                    var ListingList = _ftp.GetListing().ToList().Where(x => !x.Name.Contains(".txt"));
                    List<FileInfo> FtpFileList = new List<FileInfo>();
                    foreach (var item in ListingList)
                    {
                        FileInfo files = new FileInfo();
                        files.CreateTime = item.Modified;
                        files.Name = item.Name;
                        files.Size = item.Size;
                        FtpFileList.Add(files);
                    }
                    _ftp.Disconnect();
                    return FtpFileList;
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile(ex.Message);
                throw new FieldAccessException(ex.Message);
            }
        }

        /// <summary>
        /// 获取Pic文件列表
        /// </summary>
        /// <param name="ftpServerIP">FTP服务器IP</param>
        /// <param name="ftpUserID">FTP登录帐号</param>
        /// <param name="ftpPassword">FTP登录密码</param>
        /// <param name="ftpPicServerPort">端口</param>
        /// <returns></returns>
        public List<FileInfo> GetPicFileList(string ftpServerIP, string ftpUserID, string ftpPassword, int ftpPicServerPort)
        {
            try
            {
                using (FtpClient _ftp = new FtpClient(ftpServerIP, ftpUserID, ftpPassword, ftpPicServerPort))
                {
                    _ftp.Encoding = Encoding.UTF8;
                    _ftp.Connect();
                    var ListingList = _ftp.GetListing().ToList();
                    List<FileInfo> FtpFileList = new List<FileInfo>();
                    foreach (var item in ListingList)
                    {
                        FileInfo files = new FileInfo();
                        files.CreateTime = item.Modified;
                        files.Name = item.Name;
                        files.Size = item.Size;
                        FtpFileList.Add(files);
                    }
                    _ftp.Disconnect();
                    return FtpFileList;
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile(ex.Message);
                throw new FieldAccessException(ex.Message);
            }
        }

        /// <summary>
        /// 子目录文件列表
        /// </summary>
        /// <param name="ftpServerIP"></param>
        /// <param name="ftpUserID"></param>
        /// <param name="ftpPassword"></param>
        /// <param name="SelectDir"></param>
        /// <returns></returns>
        public List<FileInfo> GetFileNodeList(string ftpServerIP, string ftpUserID, string ftpPassword, int ftpPicServerPort, string SelectDir)
        {
            try
            {
                using (FtpClient _ftp = new FtpClient(ftpServerIP, ftpUserID, ftpPassword, ftpPicServerPort))
                {
                    _ftp.Encoding = Encoding.UTF8;
                    _ftp.Connect();
                    var ListingList = _ftp.GetListing("/" + SelectDir).ToList();
                    List<FileInfo> FtpFileList = new List<FileInfo>();
                    foreach (var ftpListItem in ListingList)
                    {
                        FileInfo fileInfo = new FileInfo
                        {
                            Name = ftpListItem.Name,
                            CreateTime = ftpListItem.Modified,
                            Size = ftpListItem.Size
                        };
                        FtpFileList.Add(fileInfo);
                    }
                    _ftp.Disconnect();
                    return FtpFileList;
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile(ex.Message);
                throw new FieldAccessException(ex.Message);
            }
        }

        /// <summary>
        /// 下载Bak文件
        /// </summary>
        /// <param name="ftpServerIP">ftp地址</param>
        /// <param name="ftpUserID">ftp账号</param>
        /// <param name="ftpPassword">ftp密码</param>
        /// <param name="saveFilePath">保存路径</param>
        /// <param name="saveFileName">保存文件名</param>
        /// <param name="downloadFileName">下载文件名</param>
        /// <param name="prog">进度条</param>
        /// <param name="label1">显示进度lable</param>
        /// <returns></returns>
        public string DownloadBakFile(string ftpServerIP, string ftpUserID, string ftpPassword, int ftpBakServerPort, string saveFilePath, string saveFileName, string downloadFileName, System.Windows.Forms.ProgressBar prog, System.Windows.Forms.Label label1)
        {
            string result = "OK";
            try
            {
                if (IsExistenceFile(saveFilePath, saveFileName))
                {
                    result = "";
                    IsAlreadyBackup = 1;
                    return result;
                }
                //生成FTP请求对象
                string path = @"" + ftpServerIP + downloadFileName;
                using (FtpClient _ftp = new FtpClient(ftpServerIP, ftpUserID, ftpPassword, ftpBakServerPort))
                {
                    BAKBTNPOWER = 1;
                    _ftp.Encoding = Encoding.Default;
                    _ftp.Connect();
                    Action<FtpProgress> progress = delegate (FtpProgress p)
                    {
                        if (prog != null)
                        {
                            //prog.Value = (int)p.Progress * 100 / 100;
                            //label1.Text = "进度:" + Math.Round(p.Progress, 2).ToString() + "%";
                            //System.Windows.Forms.Application.DoEvents();
                        }
                    };
                    _ftp.DownloadFile(@"" + saveFilePath + "/" + saveFileName, downloadFileName, FtpLocalExists.Overwrite, FtpVerify.None, progress);
                    _ftp.Disconnect();
                    return result;
                }
            }
            catch (Exception ex)
            {
                result = "Fail==>" + ex.Message;
                Logger.WriteLogFile(ex.Message);
                return result;
            }
            finally
            {
                BAKBTNPOWER = 0;
            }
        }

        /// <summary>
        /// 下载Bak文件
        /// </summary>
        /// <param name="ftpServerIP">ftp地址</param>
        /// <param name="ftpUserID">ftp账号</param>
        /// <param name="ftpPassword">ftp密码</param>
        /// <param name="saveFilePath">保存路径</param>
        /// <param name="saveFileName">保存文件名</param>
        /// <param name="downloadFileName">下载文件名</param>
        /// <returns></returns>
        public string DownloadBakFile(string ftpServerIP, string ftpUserID, string ftpPassword, int ftpBakServerPort, string saveFilePath, string saveFileName, string downloadFileName)
        {
            string result = "OK";
            try
            {
                if (IsExistenceFile(saveFilePath, saveFileName))
                {
                    result = "";
                    IsAlreadyBackup = 1;
                    return result;
                }
                //生成FTP请求对象
                string path = @"" + ftpServerIP + downloadFileName;
                using (FtpClient _ftp = new FtpClient(ftpServerIP, ftpUserID, ftpPassword, ftpBakServerPort))
                {
                    BAKBTNPOWER = 1;
                    _ftp.Encoding = Encoding.Default;
                    _ftp.Connect();
                    Logger.WriteLogFile("文件【" + downloadFileName + "】大小==" + _ftp.GetFileSize(downloadFileName) + "字节");
                    _ftp.DownloadFile(@"" + saveFilePath + "/" + saveFileName, downloadFileName, FtpLocalExists.Overwrite, FtpVerify.None);
                    _ftp.Disconnect();
                    return result;
                }
            }
            catch (Exception ex)
            {
                result = "Fail==>" + ex.Message;
                Logger.WriteLogFile(ex.Message);
                return result;
            }
            finally
            {
                BAKBTNPOWER = 0;
            }
        }

        /// <summary>
        /// 下载Pic文件
        /// </summary>
        /// <param name="ftpServerIP">FTP服务器IP</param>
        /// <param name="ftpUserID">FTP登录帐号</param>
        /// <param name="ftpPassword">FTP登录密码</param>
        /// <param name="saveFilePath">保存文件路径</param>
        /// <param name="saveFileName">保存文件名</param>
        /// <param name="downloadFileName">下载文件名</param>
        /// <param name="FolderName">文件夹名称</param>
        public string DownloadPicFile(string ftpServerIP, string ftpUserID, string ftpPassword, int ftpPicServerPort, string saveFilePath, string FolderName)
        {
            string result = "OK";
            try
            {
                if (IsExistenceFile(saveFilePath, FolderName))
                {
                    result = "";
                    return result;
                }
                using (FtpClient _ftp = new FtpClient(ftpServerIP, ftpUserID, ftpPassword, ftpPicServerPort))
                {
                    PICBTNPOWER = 1;
                    _ftp.Encoding = Encoding.Default;
                    _ftp.Connect();
                    _ftp.DownloadDirectory(@"" + saveFilePath, FolderName, FtpFolderSyncMode.Update);
                    _ftp.Disconnect();
                    return result;
                }
            }
            catch (Exception ex)
            {
                result = "Fail==>" + ex.Message;
                Logger.WriteLogFile(ex.Message);
                return result;
            }
            finally
            {
                PICBTNPOWER = 0;
            }
        }

        /// <summary>
        /// 把文件集合转换成DataTable
        /// </summary>
        /// <param name="FileName">文件名</param>
        /// <param name="FileSize">文件大小</param>
        /// <param name="fileInfos">文件信息集合</param>
        /// <returns></returns>
        public DataTable DTSource(string FileName, string FileSize, List<FileInfo> fileInfos)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add(FileName);
            dt.Columns.Add(FileSize);
            int GB = 1024 * 1024 * 1024;
            int MB = 1024 * 1024;
            int KB = 1024;
            foreach (var item in fileInfos.OrderByDescending(x => x.CreateTime))
            {
                DataRow dr = dt.NewRow();
                dr[0] = item.Name;
                //if (item.Size / GB >= 1)
                //{
                //    dr[1] = Math.Round(item.Size / (float)GB, 2) + "GB";
                //}
                //else if (item.Size / MB >= 1)
                //{
                //    dr[1] = Math.Round(item.Size / (float)MB, 2) + "MB";
                //}
                //else if (item.Size / KB >= 1)
                //{
                //    dr[1] = Math.Round(item.Size / (float)KB, 2) + "KB";
                //}
                //else
                //{
                //    dr[1] = item.Size + "Byte";
                //}
                dr[1] = item.Size + " Byte";
                dt.Rows.Add(dr);
            }
            return dt;
        }

        public bool IsExistenceFile(string Path, string FileName)
        {
            try
            {
                string pathInfo = Path + "/" + FileName;
                if (File.Exists(pathInfo))
                {
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                Logger.WriteLogFile(ex.Message);
                return false;
            }
        }
    }
}